﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace IndustryPad
{
    class RestService
    {
        
        private string baseUrl;

        public RestService(string baseUrl)
        {
            this.baseUrl = baseUrl;
        }

        public T HttpPost<T>(string Url, string body)
        {
            var request = new RequestBuilder().setUrl(baseUrl + Url).setMethod("POST").setJsonBody(body).build();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return readResponse<T>(response);
        }

        public T HttpGet<T>(string Url)
        {
            var request = new RequestBuilder().setUrl(baseUrl + Url).build();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return readResponse<T>(response);
        }

        private T readResponse<T>(HttpWebResponse response)
        {
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return JsonConvert.DeserializeObject<T>(retString);
        }

        

        class RequestBuilder
        {
            private string method;
            private string jsonBody;
            private string url;

            internal RequestBuilder setMethod(string method)
            {
                this.method = method;
                return this;
            }

            internal RequestBuilder setJsonBody(string jsonBody)
            {
                this.jsonBody = jsonBody;
                return this;
            }

            internal RequestBuilder setUrl(string url)
            {
                this.url = url;
                return this;
            }

            internal HttpWebRequest build()
            {
                if (url == null)
                    throw new Exception("没有设置请求url");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (method == null)
                    request.Method = "GET";
                else
                    request.Method = method;

                if (jsonBody != null)
                {
                    byte[] postData = Encoding.UTF8.GetBytes(jsonBody);
                    request.ContentType = "application/json";
                    request.ContentLength = postData.Length;
                    Stream myRequestStream = request.GetRequestStream();
                    myRequestStream.Write(postData, 0, postData.Length);
                    myRequestStream.Close();
                }
                return request;
            }

        }
    }
}
